package v1

import (
	"github.com/gin-gonic/gin"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/models"
	"log"
	"net/http"
)

type GetTokenAdd struct {
	Name string `json:"name"`
}

type GetTokenDelete struct {
	ID uint64 `json:"id"`
}

func GetConfTokens(c *gin.Context) {
	userID := c.MustGet("userID").(uint64)
	tokens := models.GetConfToken(userID)
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
		"message": "",
		"data": tokens,
	})
}

func GenerateConfToken(c *gin.Context) {
	userID := c.MustGet("userID").(uint64)

	var tokenName GetTokenAdd
	if err := c.BindJSON(&tokenName); err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"status": "fail",
			"message": "need token name",
		})
		return
	}

	if err := models.GenerateConfToken(userID, tokenName.Name); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": "fail",
			"message": "generate error: %s" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
		"message": "",
	})
}

func RemoveGetToken(c *gin.Context) {
	userID := c.MustGet("userID").(uint64)

	var tokenID GetTokenDelete
	if err := c.BindJSON(&tokenID); err != nil {
		log.Println(err)
		return
	}


	if err := models.DeleteConfToken(userID, tokenID.ID); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": "fail",
			"message": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
		"message": "",
	})

}